package com.voxel.sense.infomsg.module.user.personal.edit;

import android.text.TextUtils;

import com.example.com.common.app.BasePresenter;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.RegexUtils;

import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.net.helper.NetHelper;
import cyy.example.com.facotry.share.SPEngine;

/**
 * Created by ChenYiYao on 2018/9/5.
 */
public class EditBaseInfoPresenter extends BasePresenter<EditBaseInfoContract.View> implements EditBaseInfoContract.Presenter, DataSource.Callback<BaseEntity> {


    private String mStr;
    private int mType;

    public EditBaseInfoPresenter(EditBaseInfoContract.View view) {
        super(view);
    }

    @Override
    public void doEditInfo(String str, int type) {
        String name = "";
        String phone = "";
        String email = "";

        mStr = str;
        mType = type;
        if (TextUtils.isEmpty(str)) {
            mView.showError("内容不能为空");
        } else if (type == Constants.EDIT_Phone) {
            phone = str;
        } else if (type == Constants.EDIT_Email) {
            if (!RegexUtils.isEmail(str)) {
                mView.showError("请输入正确的邮箱");
                return;
            }

            email = str;
        } else if (type == Constants.EDIT_NAME) {
            name = str;
        }

        NetHelper.editUserInfo(name, phone, email, this);

    }


    @Override
    public void onDataLoaded(BaseEntity data, int reqId) {
        if (mView == null) {
            return;
        }

        if (data.isSuccess()) {
            mView.onEditSuccess();

            SPEngine.UserInfo userInfo = SPEngine.getSPEngine().getUserInfo();
            if (mType == Constants.EDIT_Phone) {
                userInfo.setPhone(mStr);
            } else if (mType == Constants.EDIT_Email) {
                userInfo.setEmail(mStr);
            } else if (mType == Constants.EDIT_NAME) {
                userInfo.setName(mStr);
            }
        }
    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView == null) {
            return;
        }

        mView.showError(strRes);
        mView.onEditFailure();
    }
}
